import { PERMISSIONS, ROLE_PERMISSIONS } from '@/config/permissionConfig'
/**
 * 将路由对象转换为可序列化的格式
 * @param {Array} routes - 路由配置数组
 * @returns {Array} 可序列化的路由配置数组
 */
export function serializeRoutes(routes) {
    return routes.map(route => {
        const serializedRoute = { ...route }

        // 处理组件
        if (route.component) {
            if (typeof route.component === 'function') {
                // 对于函数式组件，提取import路径
                const componentStr = route.component.toString()
                const matches = componentStr.match(/import\(['"]([^'"]+)['"]\)/)
                if (matches && matches[1]) {
                    serializedRoute.component = matches[1]
                }
            } else if (typeof route.component === 'string') {
                // 已经是字符串路径的情况，直接使用
                serializedRoute.component = route.component
            }
        }

        // 递归处理子路由
        if (route.children && route.children.length > 0) {
            serializedRoute.children = serializeRoutes(route.children)
        }

        return serializedRoute
    })
}

/**
 * 将序列化的路由配置转换回真实的路由对象
 * @param {Array} routes - 序列化的路由配置数组
 * @returns {Array} 真实的路由配置数组
 */
export function deserializeRoutes(routes) {
    return routes.map(route => {
        const realRoute = { ...route }

        // 将组件路径转换回动态导入函数
        if (typeof route.component === 'string') {
            realRoute.component = () => import(/* @vite-ignore */ route.component)
        }

        // 递归处理子路由
        if (route.children && route.children.length) {
            realRoute.children = deserializeRoutes(route.children)
        }

        return realRoute
    })
}

// 修改后的树形结构转换函数
export const convertToTreeData = (permissions, userPermissions = [], parentPath = '') => {
    return Object.entries(permissions)
        .map(([key, value]) => {
            if (value.code) {
                // 叶子节点，检查是否有权限
                if (!userPermissions.length || userPermissions.includes(value.code)) {
                    return {
                        label: value.name,
                        code: value.code,
                        apis: value.apis,
                        path: parentPath ? `${parentPath}.${key}` : key
                    }
                }
                return null
            } else {
                // 父节点
                const children = Object.entries(value)
                    .filter(([k, v]) => k !== 'name')
                    .reduce((acc, [k, v]) => {
                        if (typeof v === 'object') {
                            acc[k] = v
                        }
                        return acc
                    }, {})

                const convertedChildren = convertToTreeData(children, userPermissions, key)
                    .filter(Boolean) // 移除空节点

                // 如果没有子节点且不是根节点，则不显示此节点
                if (convertedChildren.length === 0 && parentPath) {
                    return null
                }

                return {
                    label: value.name || key,
                    code: key.toLowerCase(),
                    path: parentPath ? `${parentPath}.${key}` : key,
                    children: convertedChildren
                }
            }
        })
        .filter(Boolean) // 移除空节点
}

export const getRolePermissions = (role) => {
    return ROLE_PERMISSIONS[role]
}

export const getPermissionApis = (permissionCode) => {
    let apis = []
    Object.values(PERMISSIONS).forEach(category => {
        Object.values(category).forEach(subcategory => {
            if (subcategory.code === permissionCode) {
                apis = subcategory.apis
            } else if (typeof subcategory === 'object') {
                Object.values(subcategory).forEach(permission => {
                    if (permission && permission.code === permissionCode) {
                        apis = permission.apis
                    }
                })
            }
        })
    })
    return apis
}